//using Network.Diagnostics;using Windows.Networking.Connectivity;
using Network.Diagnostics;
using Windows.Networking.Connectivity;

namespace Network
{
    public class Connectivity
    {
        public delegate void ConnectivityHandler(bool available);
        public static event ConnectivityHandler AvailabilityChanged;
        public static bool IsAvailable => connectivity.IsNetworkAvailable;

        private static Connectivity connectivity = new Connectivity();
        private bool? isNetworkAvailable;
        private bool IsNetworkAvailable
        {
            get
            {
                if(!isNetworkAvailable.HasValue)
                {
                    isNetworkAvailable = CanAccess();
                }
                return isNetworkAvailable.Value;
            }
            set
            {
                if (isNetworkAvailable != value)
                {
                    isNetworkAvailable = value;
                    AvailabilityChanged?.Invoke(value);
                }
            }
        }

        private Connectivity()
        {
            NetworkInformation.NetworkStatusChanged += (s) => 
            {
                Debug.WriteLine($"NetworkStatusChanged s={s}");
                IsNetworkAvailable = CanAccess();
                Debug.WriteLine($"NetworkStatusChanged IsNetworkAvailable={IsNetworkAvailable}");
            };
            IsNetworkAvailable = CanAccess();
        }

        private bool CanAccess()
        {
            var profile = NetworkInformation.GetInternetConnectionProfile();
            if(profile != null)
            {
                Debug.WriteLine($"NetworkConnectivityLevel is {profile.GetNetworkConnectivityLevel()}");
            }
            else
            {
                Debug.WriteLine("NetworkConnectivity profile is null");
            }

            return (profile != null && (profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess || profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.LocalAccess));
        }

        static public void Refresh()
        {
            Debug.WriteLine("NetworkConnectivity refresh");
            connectivity.IsNetworkAvailable = connectivity.CanAccess();
        }
    }
}
